package com.qs.security.config;

import com.qs.security.filter.TokenVerityFilter;
import com.qs.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

@EnableGlobalMethodSecurity(securedEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserService userService;

    @Autowired
    private RsaKeyProperties rsaKeyProperties;

    /**
     * 密码加密
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 指定认证对象的由来
     *
     * @author qinyupeng
     * @since 2020-12-29 23:14:33
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }

    /**
     * 配置security安全过滤器
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭CSRF攻击防护，开启跨域
        http.csrf().disable().cors();

        //静态资源不拦截
        http.authorizeRequests().antMatchers("/css/**", "/js/**", "/img/**", "/plugins/**").permitAll();

        http.authorizeRequests()
                //允许访问登录和失败页面
                .antMatchers("/test", "/loginPage").permitAll()
                .antMatchers("/**").hasAnyRole("USER")
                .anyRequest().authenticated();

        //自定义过滤器
        http.addFilter(new TokenVerityFilter(authenticationManager(), rsaKeyProperties));

        //分布式应用，禁用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
